<template>
  <div class="designer-container">
    <el-form :model="form" label-width="120px">
      <el-form-item label="流程 Key">
        <el-input v-model="form.processKey" placeholder="例如：leaveProcess"/>
      </el-form-item>

      <el-form-item label="流程名称">
        <el-input v-model="form.processName" placeholder="例如：请假审批流程"/>
      </el-form-item>
    </el-form>

    <el-divider>审批节点配置</el-divider>

    <el-table :data="steps" style="width: 100%" border>
      <el-table-column label="节点名称" width="180">
        <template #default="{ row }">
          <el-input v-model="row.name" placeholder="请输入节点名称"/>
        </template>
      </el-table-column>

      <el-table-column label="节点类型" width="120">
        <template #default="{ row }">
          <el-select v-model="row.nodeType" placeholder="请选择">
            <el-option label="发起节点" value="start"/>
            <el-option label="审核节点" value="approval"/>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="审批类型" width="160">
        <template #default="{ row }">
          <el-select v-model="row.multiInstance" placeholder="请选择" :disabled="row.nodeType === 'start'">
            <el-option label="单签" value="none"/>
            <el-option label="会签并行" value="parallel"/>
            <el-option label="会签顺序" value="sequential"/>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="审批人类型" width="160">
        <template #default="{ row }">
          <el-select v-model="row.assigneeType" placeholder="选择类型" :disabled="row.nodeType === 'start'">
            <el-option label="指定用户" value="user"/>
            <el-option label="指定角色" value="group"/>
            <el-option label="直属领导" value="leader"/>
            <el-option label="表达式" value="expression"/>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column label="审批人值" width="220">
        <template #default="{ row }">
          <el-input
              v-if="row.nodeType === 'approval' && row.assigneeType !== 'leader'"
              v-model="row.assigneeValue"
              placeholder="请输入用户名/角色/表达式"
          />
          <span v-else-if="row.nodeType === 'approval' && row.assigneeType === 'leader'">系统默认</span>
          <span v-else>发起人自动完成</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="200">
        <template #default="{ $index }">
          <el-button size="small" @click="moveUp($index)" :disabled="$index === 0">上移</el-button>
          <el-button size="small" @click="moveDown($index)" :disabled="$index === steps.length - 1">下移</el-button>
          <el-button size="small" type="danger" @click="removeStep($index)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 16px 0">
      <el-button type="primary" @click="addStep">新增节点</el-button>
      <el-button type="success" @click="submit">生成流程图</el-button>
      <el-button type="primary" @click="saveFile">保存Bpmn</el-button>
      <el-button type="primary" @click="uploadDeployProcess" :disabled="!form.processBpmnFile">发布流程</el-button>
    </div>

    <el-divider>流程图预览</el-divider>
    <div id="bpmn-container" style="border: 1px solid #ccc; height: 500px;"></div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import BpmnViewer from 'bpmn-js'
import { generateBpmn, saveProcessInfo } from '@/api/workflow/design/designProcess.js'
import { deployProcess } from "@/api/workflow/processManager.js"

const form = reactive({
  processKey: '',
  processName: '',
  processBpmnFile: null
})

const steps = ref([
  {
    name: '发起申请',
    nodeType: 'start',
    multiInstance: 'none',
    assigneeType: 'user',
    assigneeValue: 'initiator'
  }
])

function addStep() {
  steps.value.push({
    name: '',
    nodeType: 'approval',
    multiInstance: 'none',
    assigneeType: 'user',
    assigneeValue: ''
  })
}

function removeStep(index) {
  steps.value.splice(index, 1)
}

function moveUp(index) {
  if (index > 0) {
    const item = steps.value.splice(index, 1)[0]
    steps.value.splice(index - 1, 0, item)
  }
}

function moveDown(index) {
  if (index < steps.value.length - 1) {
    const item = steps.value.splice(index, 1)[0]
    steps.value.splice(index + 1, 0, item)
  }
}

let viewer = null
const bpmnXml = ref(null)

const submit = async () => {
  const payload = {
    processKey: form.processKey,
    processName: form.processName,
    steps: steps.value
  }

  try {
    const response = await generateBpmn(JSON.stringify(payload))

    if (response.code === 200) {
      bpmnXml.value = response.data.bpmnXml

      // 渲染流程图
      if (!viewer) {
        viewer = new BpmnViewer({ container: '#bpmn-container' })
      }

      viewer.importXML(bpmnXml.value, (err) => {
        if (err) {
          ElMessage.error('流程图渲染失败')
          console.error(err)
        } else {
          ElMessage.success('流程生成成功')

          // 创建 File 对象
          const blob = new Blob([bpmnXml.value], { type: 'text/xml' })
          const file = new File([blob], `${form.processKey || 'process'}.bpmn`, { type: 'text/xml' })

          form.processBpmnFile = file
        }
      })
    } else {
      ElMessage.error(response.msg || '操作失败')
    }
  } catch (err) {
    console.error(err)
    ElMessage.error('流程生成失败')
  }
}

const saveFile = () => {
  if (!form.processBpmnFile) {
    ElMessage.warning('请先生成流程图')
    return
  }

  const a = document.createElement('a')
  const url = URL.createObjectURL(form.processBpmnFile)
  a.href = url
  a.download = `${form.processKey || 'process'}.bpmn`
  a.click()
  URL.revokeObjectURL(url)
}

const uploadDeployProcess = async () => {
  if (!form.processBpmnFile) {
    ElMessage.error('请先生成 BPMN 文件')
    return
  }

  try {
    // 构造 FormData 并直接添加文件
    const formData = new FormData()
    formData.append('name', form.processName)
    formData.append('file', form.processBpmnFile)

    // 直接调用部署接口
    const res = await deployProcess(formData)

    if (res.code === 200) {
      ElMessage.success('流程部署成功')
      // 可选：保存流程信息
      await saveProcessInfo({
        processName: form.processName,
        processKey: form.processKey,
        bpmnXml: bpmnXml.value,
        bpmnFileUrl: res.fileUrl || ''
      })
    } else {
      ElMessage.error(res.msg || '流程部署失败')
    }
  } catch (error) {
    console.error('部署异常:', error)
    ElMessage.error('流程部署失败')
  }
}
</script>

<style scoped>
.designer-container {
  padding: 20px;
}
</style>
